import React, {useEffect, useRef, useState} from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  Animated,
  Switch,
  Pressable,
} from 'react-native';

// RN component for performance testing: a long ScrollView and a switch to toggle whether scrollTo uses animation
export default function App() {
  const [animEnabled, setAnimEnabled] = useState(true); // scrollTo 动画
  const [globalAnimEnabled, setGlobalAnimEnabled] = useState(true); // ✅ 新增：整体呼吸动画开关

  const scrollRef = useRef(null);
  const approxItemHeight = 90;

  // 全局 scale 动画
  const globalScale = useRef(new Animated.Value(1)).current;
  const useNativeDriverState = false;

  // ✅ 控制整体呼吸动画是否启用
  useEffect(() => {
    if (!globalAnimEnabled) {
      globalScale.stopAnimation();
      globalScale.setValue(1); // 关闭时复位
      return;
    }

    const loop = Animated.loop(
      Animated.sequence([
        Animated.timing(globalScale, {
          toValue: 1.30,
          duration: 600,
          useNativeDriver: useNativeDriverState,
        }),
        Animated.timing(globalScale, {
          toValue: 1.0,
          duration: 600,
          useNativeDriver: useNativeDriverState,
        }),
      ]),
    );

    loop.start();
    return () => loop.stop();
  }, [globalAnimEnabled]);

  // create a large list of items for testing
  const ITEMS = Array.from({length: 100}, (_, i) => ({
    id: i + 1,
    title: `测试项 #${i + 1}`,
  }));

  // helper to scroll to a specific vertical offset
  const doScrollTo = (y: any) => {
    if (!scrollRef.current) return;
    // scrollTo's `animated` parameter is controlled by animEnabled
    scrollRef.current.scrollTo({y, animated: animEnabled});
  };

  // convenience actions
  const scrollToTop = () => doScrollTo(0);
  const scrollToMiddle = () => {
    // approximate middle: half of total content height
    // since we don't know exact content height, use item height * index
    const middleIndex = Math.floor(ITEMS.length / 2);
    doScrollTo(middleIndex * approxItemHeight);
  };
  const scrollToBottom = () => {
    doScrollTo(ITEMS.length * approxItemHeight);
  };

  return (
    <View style={styles.container}>
      <View style={styles.controls}>
        <Text style={styles.controlLabel}>
          useNativeDriverState {useNativeDriverState ? '启用' : '禁用'}
        </Text>

        <Text style={styles.controlLabel}>滚动动画</Text>
        <Switch value={animEnabled} onValueChange={setAnimEnabled} />

        {/* ✅ 新增：整体动画开关 */}
        <Text style={styles.controlLabel}>整体动画</Text>
        <Switch
          value={globalAnimEnabled}
          onValueChange={setGlobalAnimEnabled}
        />

        <Pressable onPress={scrollToTop} style={styles.actionButton}>
          <Text style={styles.actionText}>滚到顶部</Text>
        </Pressable>
        <Pressable onPress={scrollToMiddle} style={styles.actionButton}>
          <Text style={styles.actionText}>滚到中间</Text>
        </Pressable>
        <Pressable onPress={scrollToBottom} style={styles.actionButton}>
          <Text style={styles.actionText}>滚到底部</Text>
        </Pressable>
      </View>

      <ScrollView
        ref={scrollRef}
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={true}>
        {ITEMS.map((item, idx) => (
          <Pressable
            key={item.id}
            onPress={() => doScrollTo(idx * 90)}
            style={({pressed}) => [styles.card, pressed && {opacity: 0.8}]}>
            {/* ✅ 单个卡片的动画内容 */}
            <Animated.View style={{transform: [{scale: globalScale}]}}>
              <Text style={styles.cardTitle}>{item.title}</Text>
              <Text style={styles.cardBody} numberOfLines={3}>
                用于填充 ScrollView 的示例文本，用于性能测试。
              </Text>
            </Animated.View>
          </Pressable>
        ))}

        <View style={styles.footerSpacer} />
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {flex: 1, paddingTop: 44, backgroundColor: '#f7f7f7'},
  controls: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 12,
    gap: 8,
    marginBottom: 8,
    flexWrap: 'wrap',
  },
  controlLabel: {fontSize: 16},
  toggleButton: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    backgroundColor: '#3b82f6',
    borderRadius: 6,
  },
  toggleButtonText: {color: 'white', fontSize: 14},
  actionButton: {
    paddingHorizontal: 10,
    paddingVertical: 6,
    backgroundColor: '#10b981',
    borderRadius: 6,
  },
  actionText: {color: 'white'},
  scrollContent: {paddingHorizontal: 12, paddingBottom: 60},
  card: {
    backgroundColor: 'white',
    borderRadius: 8,
    padding: 12,
    marginBottom: 10,
    minHeight: 70,
    shadowColor: '#000',
    shadowOpacity: 0.04,
    shadowRadius: 4,
    elevation: 1,
    justifyContent: 'center',
  },
  cardTitle: {fontSize: 16, fontWeight: '600', marginBottom: 6},
  cardBody: {fontSize: 13, color: '#444'},
  footerSpacer: {height: 120},
});
